// pages/order/order.js
let {
  getSite,
  updateInventory
} = require("../../api/order")
var appInfo = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buyList: [],
    shoopsNum: 0,
    site: {},
    allPrice: 0
  },
  async onClickButton() {
    if (this.data.site.name == "您当前还没有地址，赶快添加吧") {
      wx.showToast({
        title: '请添加地址',
        icon: "none"
      })
      return
    }
    this.data.buyList.forEach(async v => {
      let num = v.inventory - v.num;
      await updateInventory({ inventory: num, id: v.id })
    })
    let shoop = wx.getStorageSync('shoop')
    this.data.buyList.forEach(item => {
      shoop.slice().filter((v, i) => {
        if (v.id == item.id || v.info == item.info) {
          shoop.splice(i, 1)
        }
      })
    })

    wx.setStorageSync('shoop', shoop)
    wx.removeStorageSync('buyList')
    wx.showToast({
      title: "交易完成"
    })
    setTimeout(() => {
      wx.navigateBack()
    }, 1000)
  },
  sikesite() {
    wx.navigateTo({
      url: '/pages/site/site',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    let buyList = wx.getStorageSync('buyList')
    this.setData({
      buyList,
      shoopsNum: buyList.length
    })
    let siteS = {};
    let r = await getSite({ uid: appInfo.globalData.openid, priority: 1 })
    if (!r.data.length) {
      let r1 = await getSite({ uid: appInfo.globalData.openid })
      if (r1.data.length) {
        siteS = r1.data[0]
      } else {
        siteS.name = "您当前还没有地址，赶快添加吧"
      }
    } else {
      siteS = r.data[0]
    }
    // if (!r.data.length) {
    //   r.data.push({ name: "您当前还没有地址，赶快添加吧" })
    // }
    this.setData({
      site: siteS
    })
    let allPrice = 0
    this.data.buyList.forEach(v => {
      return allPrice += v.newPrice * v.num
    })
    this.setData({
      allPrice
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})